package com.lovepick.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.lovepick.GlobalApp;
import com.lovepick.R;
import com.lovepick.bean.User;
import com.lovepick.http.AvatarTask;
import com.lovepick.util.BaseUtils;

public class UserInfoFragment extends Fragment
{
	private static final String TAG = "UserInfoAcitivy";
	private String mNickName;
	private String mAvatar;
	private TextView mNickNameView;
	private ImageView mAvatarView;

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);

		findViews();

		User user = GlobalApp.getInstance().getLoginInfo();
		this.mNickName = user.getNickName();
		this.mAvatar = user.getAvatar();
		Log.i(TAG, "NickName: " + mNickName);
		Log.i(TAG, "Avatar: " + mAvatar);
		mNickNameView.setText(mNickName);

		Log.i(TAG, "###开始获取用户头像###");
		if (mAvatar.equals("0"))
		{
			Log.i(TAG, "---使用默认头像");
			mAvatarView.setImageDrawable(getResources().getDrawable(R.drawable.avatar));
		}
		else
		{
			Bitmap bitmap = BaseUtils.getAvatarFromLocal(mNickName);

			if (bitmap != null)
			{
				Log.i(TAG, "---本地存有头像, 直接加载.");
				mAvatarView.setImageBitmap(bitmap);
			}
			else
			{
				Log.i(TAG, "---本地未保存头像---");
				if (BaseUtils.getNetworkState())
				{
					Log.i(TAG, "---联网获取头像.");
					new GetAvatarTask().execute(new String[] { mAvatar,
							mNickName });
				}
				else
				{
					Log.i(TAG, "---没有网络连接, 使用默认头像.");
					mAvatarView.setImageDrawable(getResources().getDrawable(
							R.drawable.avatar));
				}
			}
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.user_info, container, false);
	}

	private void findViews()
	{
		mNickNameView = (TextView) getActivity().findViewById(R.id.txv_nick_name);
		mAvatarView = (ImageView) getActivity().findViewById(R.id.img_user_avatar);
	}

	private class GetAvatarTask extends AvatarTask
	{

		@Override
		protected void onPostExecute(Bitmap result)
		{
			// TODO Auto-generated method stub
			if (result != null)
			{
				mAvatarView.setImageBitmap(result);
			}
			else
			{
				mAvatarView.setImageDrawable(getResources().getDrawable(R.drawable.avatar));
			}
		}

	}

}
